# -*- coding: cp936 -*-
import http.client
import http.cookiejar
import http.cookies
import os
import queue
import random
import re
import socket
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request

NUM_THREADS = 1
HTTP_TIMEOUT = 30

music_list = None
music_list_lock = threading.Lock()
current_ip_index = 0
download_dir = None
current_album_index = 0

def GetDownloadLink(url):
  print('GetDownloadLink. url: ' + url)
  opener = urllib.request.FancyURLopener()
  opener.addheaders = [
      # User-Agent is not necessary.
      ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0'),
      ('Cookie', 'SingLinkGate=24420f601af54afa991ba7e73db61c02; 5sing_auth=YCmodlxOUiaoSEKD/dkNBw1tnbVm/YaLazHeiepyndhdbAW24gQGTw==; UserSignInLog=1'),
      ]
  f = opener.open(url)
  html = f.read().decode()

  # p = re.compile('SongID=([^&]+)&.*SongType=([^"]+)"')
  p = re.compile('<a href="(DownFile\.aspx\?SongID=[^"]+)"')
  match = p.findall(html)
  # link = 'http://bz.5sing.com/DownFile.aspx?SongID=' + match[0][0] + '&SongType=' + match[0][1]
  link = 'http://bz.5sing.com/' + match[0]
  print('GetDownloadLink. download link: ' + link)

  p = re.compile('<h1>[^<]*<a[^>]+>([^<]+)<\/a>')
  match = p.findall(html)
  filename = match[0]

  return link, filename

def GetMp3List(url):
  try:
    webdata = urllib.request.urlopen(url).read().decode()
  except:
    print("Error while reading the web...")
    sys.exit(1)

  p = re.compile('<h3>([^<]+)<\/h3>')
  album = p.findall(webdata)[1]

  p = re.compile('<td><a href="(.+sid=[^"]+)"[^>]+><img[^>]+><\/a><\/td>')
  music_content = p.findall(webdata)

  print('Get ' + str(music_content.__len__()) + ' urls from ' + url)
  return album, music_content

def GetAllMp3Url():
  pages = [
      # "zj.aspx?zjid=50e5ddbce2dafe143cad006e",
      # "zj.aspx?zjid=50e31c8ee2dafe0b700899b5",
      # "zj.aspx?zjid=504b081e308c050f6825a14b",
      "zj.aspx?zjid=504af438308c050f7401e497",
      "zj.aspx?zjid=503999e0308c051350081c92",
      "zj.aspx?zjid=5039212a308c0513c03f8638",
      "zj.aspx?zjid=5037500d308c052ff811fe4f",
      "zj.aspx?zjid=503322a8308c050ef0dae6a6",
      "zj.aspx?zjid=502ec5e2308c051c64a2ff2c",
      "zj.aspx?zjid=5022d124308c0515ac106213",
      # "zj.aspx?zjid=5010606f308c0508448f4abc",
      "zj.aspx?zjid=500d8201308c0516ccb532bb",
      "zj.aspx?zjid=500ced57308c0516ccb52a07",
      "zj.aspx?zjid=500c7b4c308c051a603f45a9",
      # "zj.aspx?zjid=50086b18308c0510200c3393",
      # "zj.aspx?zjid=5008603d308c0512b4042497",
      "zj.aspx?zjid=5006edfb308c051c18cedcc8",
      "zj.aspx?zjid=5006dbea308c050d58df09ec",
      "zj.aspx?zjid=50057de5308c051628a015de",
      "zj.aspx?zjid=500568fa308c0501143be23c",
      "zj.aspx?zjid=4ffe87a8308c05162c809e9a",
      "zj.aspx?zjid=4ffd47cc308c052140f1ab1d",
      "zj.aspx?zjid=4ffc2954308c0527e0b34280",
      "zj.aspx?zjid=4ffafb53308c0525041c5360",
      "zj.aspx?zjid=4ff86796308c052758f47da6",
      "zj.aspx?zjid=4ff78e86308c052758f471d8",
      "zj.aspx?zjid=4ff72795308c0519c8d24cad",
      ];
  musics = []
  for p in pages:
    url = "http://11168141.5sing.com/" + p
    album, l = GetMp3List(url)
    musics.append((album, l))
  return musics

def Download(url):
  try:
    link, filename = GetDownloadLink(url)
    fullpath = os.path.join(download_dir, filename)
    print('Downloading ' + link)
  
    f = open(fullpath + '.mp3', 'wb')
    opener = urllib.request.FancyURLopener()
    opener.addheaders = [
        # User-Agent is not necessary.
        ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0'),
        ('Cookie', 'SingLinkGate=24420f601af54afa991ba7e73db61c02; 5sing_auth=YCmodlxOUiaoSEKD/dkNBw1tnbVm/YaLazHeiepyndhdbAW24gQGTw==; UserSignInLog=1'),
        ]
    data = opener.open(link).read()
    f.write(data)
    f.close()
  except:
    print('Download error!')

def WorkerThread():
  global music_list, music_list_lock, current_ip_index
  while True:
    idx = 0
    proxy = None

    music_list_lock.acquire()
    idx = current_ip_index
    current_ip_index += 1
    music_list_lock.release()

    if idx >= music_list[current_album_index][1].__len__():
      break;
    url = music_list[current_album_index][1][idx]
    Download(url)

if __name__ == '__main__':
  socket.setdefaulttimeout(HTTP_TIMEOUT)  # http time out
  music_list = GetAllMp3Url()

  current_album_index = 0
  for i in music_list:
    download_dir = os.path.join('E:\\get5sing', i[0])
    if os.path.exists(download_dir)==False:
      os.mkdir(download_dir)

    threads = []
    for n in range(NUM_THREADS - 1):  # the last thread is main thread
      t = threading.Thread(target = WorkerThread)
      t.setDaemon(True)
      t.start()
      threads.append(t)
  
    WorkerThread()  # main thread work as a worker

    for t in threads:
      t.join()
    current_album_index += 1
